class Manage::DocumentsController < ApplicationController
  include Security::Session::Access
  include Utils::Url
  include Intranet::FileSystem
  include UserData

  def list
    @category_pages, @categories = paginate(:document_category, :per_page => 10)
  end

  def create
    case request.method
    when :post
      if params[:commit] == "Cancel"
        redirect_to(:action => "list")
        return
      end
      params[:category].delete(:id)
      @category = DocumentCategory.new(params[:category])
      @category.updated_by = current_updater_id
      if @category.save
        assign_category_pages
        flash[:notice] = "Document category successfully created"
        redirect_to(:action => "list")
      end
    else
      @category = DocumentCategory.new
    end
  end

  def show
    @page = Page.find(id_param)
  end

  def update
    case request.method
    when :post
      if params[:commit] == "Cancel"
        redirect_to(:action => "list")
        return
      end
      @category = DocumentCategory.find(params[:category][:id])
      params[:category].delete(:id)
      @category.attributes = params[:category]
      @category.updated_by = current_updater_id
      if @category.save
        assign_category_pages
        flash[:notice] = "Document category successfully updated"
        redirect_to(:action => "list")
      end
    else
      @category = DocumentCategory.find(id_param)
    end
  end

  def manage_files
    @category = DocumentCategory.find(id_param)
    case request.method
    when :post
      case params[:commit]
      when "Cancel"
        redirect_to(:action => "list")
        return
      when "Add file"
        @document = Document.new(params[:document])
        @document.document_category_id = @category.id
        @document.updated_by = current_updater_id
        if @document.save
          configure_document_version
          if @document_version.save 
            @document.reload
            add_create_notice_to_home_page
            if current_user_can_manage_document_category?(@category.id)
              session[:allowed_urls] << {:controller => "/manage/documents", :action => "manage_file_versions", :id => @document.id}
              session[:allowed_urls] << {:controller => "/manage/documents", :action => "delete_file", :id => @document.id}

            end
            flash[:notice] = "File successfully added"
            redirect_to(:action => "manage_files", :id => @category.id)
            return
          else
            @document.destroy
            @document = Document.new
          end
        end
      end
    else
      @document = Document.new
    end
  end

  def manage_file_versions
    @document = Document.find(id_param) 
    case request.method
    when :post
      case params[:commit]
      when "Cancel"
        redirect_to(:action => "manage_files", :id => @document.document_category.id)
        return
      when "Update"
        configure_document_version
        @document.attributes = params[:document]
        @document.updated_by = current_updater_id
        if @document.save
          if @document_version.valid?
            if @document_version.save 
              @document_version.make_current
              @document.reload
              add_update_notice_to_home_page
              flash[:notice] = "Document successfully updated and revised."
              redirect_to(:action => "manage_files", :id => @document.document_category_id)
            end
          else
              flash[:notice] = "Document successfully updated"
              redirect_to(:action => "manage_files", :id => @document.document_category_id)
          end
        end
      end
    else
      @document_version = @document.current_version
    end
  end

  def delete
    category = DocumentCategory.find(id_param)
    dirname = category.directory_name.dup
    category.destroy
    delete_documents_dir(dirname)
    redirect_to(:action => "list")
  end

  def delete_file
    d = Document.find(id_param)
    cat_id = d.document_category.id
    d.destroy
    redirect_to(:action => "manage_files", :id => cat_id) 
  end

  def set_file_version
    dv = DocumentVersion.find(id_param)
    dv.make_current
    redirect_to(:action => "manage_file_versions", :id => dv.document.id) 
  end

  def delete_file_version
    dv = DocumentVersion.find(id_param)
    doc_id = dv.document.id
    dv.destroy
    redirect_to(:action => "manage_file_versions", :id => doc_id) 
  end

  private
    def assign_category_pages
      #Clear orphans
      pages = @category.page.dup 
      pages.each do |cat_page|
        @category.page.delete(cat_page) unless param?("page_#{cat_page.id}")
      end

      params.each do |key,value|
        if key =~ /^page_/
          pg_id = get_id_from_param(key)
          unless @category.has_page?(pg_id)
            pg = Page.find(pg_id) 
            pg.current_folder.assign_document_category_to_groups(@category)
            @category.page << pg
          end
        end
      end
    end
    
    def configure_document_version
      @document_version = DocumentVersion.new
      @document_version.document_id = @document.id
      @document_version.location = relative_documents_dir + "#{@document.document_category.directory_name}/"
      @document_version.attributes = params[:document_version]
      @document_version.is_current = true
      if @document.document_version && @document.document_version.length > 0
        @document_version.version = @document.document_version[0].version + 1
      end
      @document_version.updated_by = current_updater_id
    end

    def add_create_notice_to_home_page
      return unless params[:add_to_home_page]
      msg = Message.new
      msg.title = "New document: #{@document.title}"
      doc_link = document_link
      msg.details = doc_link
      msg.expires_on = Time.now.next_month
      msg.updated_by = current_user_id
      msg.save
    end

    def add_update_notice_to_home_page
      return unless params[:add_to_home_page]
      msg = Message.new
      msg.title = "Document update: #{@document.title}"
      doc_link = document_link
      msg.details = doc_link
      msg.expires_on = Time.now.next_month
      msg.updated_by = current_user_id
      msg.save
    end

    def document_link
      return "<a href=\"/pages/view_document/#{@document.current_version.id}\">Download</a>"
    end
end
